package com.testplatfrom.project.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.testplatfrom.common.core.exception.project.ProjectException;
import com.testplatfrom.common.security.utils.SecurityUtils;
import com.testplatfrom.project.domain.*;
import com.testplatfrom.project.domain.dto.environment.TestplatfromEnvironmentDetail;
import com.testplatfrom.project.domain.dto.environment.TestplatfromEnvironmentPageVo;
import com.testplatfrom.project.domain.dto.environment.TestplatfromEnvironmentVo;
import com.testplatfrom.project.domain.dto.environment.TestplatfromProjectEnvirmentPage;
import com.testplatfrom.project.domain.dto.project.TestplatfromProjectPageVo;
import com.testplatfrom.project.mapper.TestplatfromEnvironmentMapper;
import com.testplatfrom.project.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 杨森
 * @since 2023-07-27
 */
@Service
public class TestplatfromEnvironmentServiceImpl extends ServiceImpl<TestplatfromEnvironmentMapper, TestplatfromEnvironment> implements TestplatfromEnvironmentService {

    @Autowired
    private TestplatfromProjectService testplatfromProjectService;

    @Autowired
    private TestplatfromHttpconfigurationService testplatfromHttpconfigurationService;

    @Autowired
    private TestplatfromDatabaseService testplatfromDatabaseService;

    @Autowired
    private TestplatfromAssertService testplatfromAssertService;

    @Autowired
    private TestplatfromVariableService testplatfromVariableService;


    @Autowired
    private TestplatfromProjectmemberService testplatfromProjectmemberService;

    //环境列表
    @Override
    public TestplatfromEnvironmentPageVo listTestplatfromEnvironment(TestplatfromProjectEnvirmentPage testplatfromProjectEnvirmentPage) {
        TestplatfromProjectEnvirmentPage projectEnvirmentPage = new TestplatfromProjectEnvirmentPage();
        //当不存在项目id时则查询出所有项目
        if (ObjectUtil.isEmpty(testplatfromProjectEnvirmentPage.getTestplatfromProjectId())) {
            LambdaQueryWrapper<TestplatfromEnvironment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper
                    .eq(ObjectUtil.isNotEmpty(testplatfromProjectEnvirmentPage.getEnvironmentName()), TestplatfromEnvironment::getEnvironmentName, testplatfromProjectEnvirmentPage.getEnvironmentName())
                    .eq(ObjectUtil.isNotEmpty(testplatfromProjectEnvirmentPage.getCreateBy()), TestplatfromEnvironment::getCreateBy, testplatfromProjectEnvirmentPage.getCreateBy())
                    .orderByDesc(TestplatfromEnvironment::getCreateTime);
            projectEnvirmentPage = this.page(testplatfromProjectEnvirmentPage, lambdaQueryWrapper);

            //如果是admin则返回全部项目
            if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
                //判断项目该人员包括的项目
                List<TestplatfromProjectmember> testplatfromProjectmembers = testplatfromProjectmemberService.list(new LambdaQueryWrapper<TestplatfromProjectmember>().eq(TestplatfromProjectmember::getUserId, SecurityUtils.getUserId()));
                //若list不为空
                if (!CollectionUtils.isEmpty(testplatfromProjectmembers)) {
                    List<String> collect = testplatfromProjectmembers.stream().map(TestplatfromProjectmember::getTestplatfromProjectId).collect(Collectors.toList());
                    lambdaQueryWrapper.in(TestplatfromEnvironment::getTestplatfromProjectId, collect);
                } else {
                    //若为空 则该用户没有项目权限 则返回空列表
                    return TestplatfromEnvironmentPageVo.builder()
                            .size(testplatfromProjectEnvirmentPage.getSize())
                            .current(testplatfromProjectEnvirmentPage.getCurrent())
                            .total(testplatfromProjectEnvirmentPage.getTotal())
                            .build();
                }
            }
        } else {
            //按项目id查询出对应项目
            TestplatfromProject testplatfromProject = testplatfromProjectService.getById(testplatfromProjectEnvirmentPage.getTestplatfromProjectId());
            if (ObjectUtil.isNull(testplatfromProject)) {
                throw new ProjectException("项目不存在");
            }
            //查询出当前项目下所有环境列表
            LambdaQueryWrapper<TestplatfromEnvironment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(TestplatfromEnvironment::getTestplatfromProjectId, testplatfromProjectEnvirmentPage.getTestplatfromProjectId())
                    .eq(ObjectUtil.isNotEmpty(testplatfromProjectEnvirmentPage.getEnvironmentName()), TestplatfromEnvironment::getEnvironmentName, testplatfromProjectEnvirmentPage.getEnvironmentName())
                    .eq(ObjectUtil.isNotEmpty(testplatfromProjectEnvirmentPage.getCreateBy()), TestplatfromEnvironment::getCreateBy, testplatfromProjectEnvirmentPage.getCreateBy())
                    .orderByDesc(TestplatfromEnvironment::getCreateTime);
            projectEnvirmentPage = this.page(testplatfromProjectEnvirmentPage, lambdaQueryWrapper);
        }
        //对数据进行拼接
        TestplatfromEnvironmentPageVo environmentPageVo = TestplatfromEnvironmentPageVo.builder().current(projectEnvirmentPage.getCurrent())
                .size(projectEnvirmentPage.getSize())
                .total(projectEnvirmentPage.getTotal()).build();
        List<TestplatfromEnvironment> records = projectEnvirmentPage.getRecords();
        List<TestplatfromEnvironmentVo> TestplatfromEnvironmentVolist = new ArrayList<>();
        for (TestplatfromEnvironment record : records) {
            TestplatfromEnvironmentVo testplatfromEnvironmentVo = TestplatfromEnvironmentVo.builder().build();
            BeanUtils.copyProperties(record, testplatfromEnvironmentVo);
            TestplatfromEnvironmentVolist.add(testplatfromEnvironmentVo);
        }
        environmentPageVo.setRecords(TestplatfromEnvironmentVolist);
        return environmentPageVo;
    }


    /**
     * @param testplatfromEnvironmentDetail 新增环境参数
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addTestplatfromEnvironment(TestplatfromEnvironmentDetail testplatfromEnvironmentDetail) {
        //按项目id查询出对应项目
        TestplatfromProject testplatfromProject = testplatfromProjectService.getById(testplatfromEnvironmentDetail.getTestplatfromProjectId());
        if (ObjectUtil.isNull(testplatfromProject)) {
            throw new ProjectException("项目不存在");
        }
        //新增环境
        TestplatfromEnvironment testplatfromEnvironment = TestplatfromEnvironment.builder().testplatfromProjectId(testplatfromEnvironmentDetail.getTestplatfromProjectId())
                .environmentName(testplatfromEnvironmentDetail.getEnvironmentName())
                .createBy(SecurityUtils.getUsername())
                .createTime(LocalDateTime.now())
                .build();
        this.save(testplatfromEnvironment);
        //HTTP配置新增
        testplatfromHttpconfigurationService.HttpConfigCheck(testplatfromEnvironmentDetail.getTestplatfromHttpconfigurationList(), testplatfromEnvironment.getEnvironmentId(), true);
        //数据库配置新增
        testplatfromDatabaseService.databaseCheck(testplatfromEnvironmentDetail.getTestplatfromDatabaseList(), testplatfromEnvironment.getEnvironmentId(), true);
        //全局断言新增
        testplatfromAssertService.addOrUpdateTestplatfromAssert(testplatfromEnvironmentDetail.getTestplatfromAssertList(), testplatfromEnvironment.getEnvironmentId(), true);
        //全局通用配置
        testplatfromVariableService.addOrUpdateTestplatfromVariableList(testplatfromEnvironmentDetail.getTestplatfromVariableList(), testplatfromEnvironment.getEnvironmentId(), true);
        return true;
    }

    @Override
    public TestplatfromEnvironmentDetail getTestplatfromEnvironment(String environmentId) {
        TestplatfromEnvironment testplatfromEnvironment = getById(environmentId);
        if (ObjectUtil.isNull(testplatfromEnvironment)) {
            throw new ProjectException("环境不存在");
        }
        //HTTP配置获取
        List<TestplatfromHttpconfiguration> testplatfromHttpconfigurations = testplatfromHttpconfigurationService.getHttpConfigDetail(environmentId);
        //数据库配置获取
        List<TestplatfromDatabase> testplatfromDatabaseList = testplatfromDatabaseService.getDatabaseDetail(environmentId);
        //全局断言配置
        List<TestplatfromAssert> testplatfromAssertList = testplatfromAssertService.getTestplatfromAssert(environmentId);
        //全局通用配置
        List<TestplatfromVariable> testplatfromVariableList = testplatfromVariableService.getTestplatfromVariableList(environmentId);
        return TestplatfromEnvironmentDetail.builder().environmentName(testplatfromEnvironment.getEnvironmentName())
                .testplatfromHttpconfigurationList(testplatfromHttpconfigurations)
                .testplatfromDatabaseList(testplatfromDatabaseList)
                .testplatfromAssertList(testplatfromAssertList)
                .testplatfromVariableList(testplatfromVariableList).testplatfromProjectId(testplatfromEnvironment.getTestplatfromProjectId()).build();
    }

    @Override
    public Boolean deleteEnviroment(String environmentId) {
        TestplatfromEnvironment testplatfromEnvironment = getById(environmentId);
        if (ObjectUtil.isNull(testplatfromEnvironment)) {
            throw new ProjectException("环境不存在");
        }
        //删除HTTP配置
        testplatfromHttpconfigurationService.remove(new LambdaQueryWrapper<TestplatfromHttpconfiguration>().eq(TestplatfromHttpconfiguration::getEnvironmentId, environmentId));
        //数据库配置获取
        testplatfromDatabaseService.remove(new LambdaQueryWrapper<TestplatfromDatabase>().eq(TestplatfromDatabase::getEnvironmentId, environmentId));
        //全局断言配置
        testplatfromAssertService.remove(new LambdaQueryWrapper<TestplatfromAssert>().eq(TestplatfromAssert::getEnvironmentId, environmentId));
        //全局通用配置
        testplatfromVariableService.remove(new LambdaQueryWrapper<TestplatfromVariable>().eq(TestplatfromVariable::getEnvironmentId, environmentId));
        return removeById(environmentId);
    }

}
